# set async_mode to 'threading', 'eventlet', 'gevent' or 'gevent_uwsgi' to
# force a mode else, the best mode is selected automatically from what's
# installed
async_mode = None

from flask import Flask, render_template
import socketio
import json

sio = socketio.Server(async_mode=async_mode)
app = Flask(__name__)
app.wsgi_app = socketio.WSGIApp(sio, app.wsgi_app)

data_all = ""
i = 0
count = 0

@app.route('/')
def index():
    return render_template('latency.html')

@sio.event
def ping_from_client(sid, data):
    print(data)
    global i
    print("第{}次接收数据".format(i))
    i = i + 1
    with open('../data/temp.json', 'a') as f1:
        f1.write(json.dumps(data))  # 写入时对文件进行序列化
    sio.emit('pong_from_server', room=sid)

    """
    if type(data) is int:
        global count
        count = data
        sio.emit('pong_from_server', room=sid)
    else:
        global data_all
        data_all += data
        global i
        print("第{}次接收数据".format(i))
        i = i + 1
        if i < count:
            sio.emit('pong_from_server', room=sid)
        else:
            with open('../data/transferData.json', 'w') as f1:
                f1.write(json.dumps(data_all))  # 写入时对文件进行序列化
    """



if __name__ == '__main__':
    if sio.async_mode == 'threading':
        # deploy with Werkzeug
        app.run(threaded=True)
    elif sio.async_mode == 'eventlet':
        # deploy with eventlet
        import eventlet
        import eventlet.wsgi
        eventlet.wsgi.server(eventlet.listen(('', 5010)), app)
    else:
        print('Unknown async_mode: ' + sio.async_mode)
